import axios from 'axios'

const axiosInstance = axios.create({
    baseURL: "http://localhost:5069",
    timeout: 5000,
})

// 获取存储的token
const token = localStorage.getItem('token')
if (token) {
    axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`
}

// 请求拦截器
axiosInstance.interceptors.request.use(config => {
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器
axiosInstance.interceptors.response.use(response => {
    return response
}, error => {
    // 处理401错误（未授权）
    if (error.response && error.response.status === 401) {
        localStorage.removeItem('token')
        window.location.href = '/login'
    }
    return Promise.reject(error)
})

// 导出封装方法
export { axiosInstance }